from DataFilter import DataFilter
from infra.logging import logger

class UrlDomainFilter(DataFilter):

	def __init__(self, rootUrl):
		self.rootUrl_ = rootUrl

	# return: abs url,rel url if ok, 2 empty strings otherwise
	def filter(self, url):
		try:
			if url[0] == '/': 
				if len(url) > 1:
					return self.rootUrl_ + url, url
				else:
					return self.rootUrl_, url

			if url.find(self.rootUrl_) != -1:
				rel_url = url.replace(self.rootUrl_, "")
				if not rel_url:
					rel_url = "/"
				return url, rel_url

		except IndexError:
			pass

		if not self.isFromDomain(url):
			log = logger.getLogger()
			log.debug("url = %s, is not from %s domain, hence is filtered." % (url, self.rootUrl_))
			return "", ""
		else:
			return url, url


	def isFromDomain(self, url):
		rv = False
		rootUrlToks = self.rootUrl_.split('.')
		if len(rootUrlToks) >= 3:	# <prot>.<domain>.<suffix>
			if url.find(rootUrlToks[1]) != -1:
				rv = True 
		return rv
